<?php
/**
 *	InstallUtils.php - SmitBoard Installation & Upgradation Framework ;-)
 *	This is Smit Matterhorn - Build 24109
 *	
 *
 * @author		The SmitBoard Team & Community
 * @license		GNU GPL v3
 * @link		http://smitboard.sf.net
 * @since		Matterhorn
 */
 
class InstallUtils
{
	private static $instance;
	
	public $base;

	public $output;

	public $installer;

	public $step;

	private function __construct()
	{
		$this->base = SmitBase::getInstance();
		$this->base->init_generic();
	}

    public function __clone()
    {
        trigger_error('cloning denied.', E_USER_ERROR);
    }

	static function getInstance()
	{
		if(!is_object(self::$instance))
		{
			self::$instance = new self;
		}
		return self::$instance;
	}
	
	public function set_db_settings($driver, $host, $username, $password, $database, $prefix, $persist = 0, $port = NULL)
	{
		$this->base->db_vars = array(
			'db_driver' => $driver,
			'db_host' => $host,
			'db_port' => $port,
			'db_user' => $username,
			'db_password' => $password,
			'db_name' => $database,
			'db_prefix' => $prefix,
			'db_persist' => $persist
		);
		return TRUE;
	}
	public function db_connect()
	{
		return $this->base->load('database');
	}

	public function template($file, $vars = array(), $return = FALSE)
	{
		$path = './templates/' . $file . EXT;
		if(!file_exists($path)) $this->base->error('The installation template "' . $file . '" does not exist', E_OUTPUT, 'Full Path: ' . $path);
		
		extract($vars);
		$smit_url = $this->base->vars['root']['root_url'];
		$smit_media = $smit_url . 'templates/media/';
		ob_start();
		include $path;
		$contents = ob_get_clean();
		
		if(!$return)
		{
			print $contents;
		}
		else
		{
			return $contents;
		}
	}

	public function navigation($step)
	{
		$this->step = $step;
	}

	public function box($type, $title, $contents, $extra = '')
	{
		$boxes = array('general', 'notice', 'info', 'error');

		if(!in_array($type, $boxes)) $type = 'general';
		$this->output .= $this->template('boxes', array('type' => $type, 'title' => $title, 'contents' => $contents, 'extra' => $extra), TRUE);
	}

	public function rowset_open()
	{
		$this->output .= '				<div class="rowset">';
	}
	public function rowset_close()
	{
		$this->output .= '				</div>';
	}

	public function form_open($name, $action)
	{
		$action = str_replace('&', '&amp;', $action);
		$this->output .= '				<form name="' . $name . '" action="' . $this->base->vars['root']['root_url'] . basename($_SERVER['SCRIPT_FILENAME']) . '?' . $action . '" method="post">';
	}
	public function form_close()
	{
		$this->output .= '				</form>';
	}

	public function input($name, $value = '')
	{
		return '<input type="text" name="' . $name . '" class="form" value="' . (isset($_POST[$name]) ? $_POST[$name] : $value) . '" />';
	}

	public function form_button($name)
	{
		$this->output .= '<input type="submit" name="submit" class="button" value="' . $name . '" />';
	}

	public function green($string)
	{
		return '<span style="color: green">' . $string . '</span>';
	}

	public function red($string)
	{
		return '<span style="color: red">' . $string . '</span>';
	}

	public function blue($string)
	{
		return '<span style="color: blue">' . $string . '</span>';
	}
	public function row($title, $contents, $description = '')
	{
		if($description != '')
		{
		$description = '<p>' . $description . '</p>';
		}
		$row = '					<div class="row">
						<div class="label">
						' . $title . $description . '
						</div>
						<p>' . $contents . '</p>
					</div>';
		$this->output .= $row;
	}

	public function flush($title = '')
	{
		$heading = '';
		if($title != '')
		{
			$title .= ' - ';
		}
		if($this->installer != '')
		{
			$title .= $this->installer . ' | ';
			$heading = $this->installer;
		}
		$heading .= ' &rarr; ' . $this->step;
		$this->template('wrapper', array('title' => $title, 'heading' => $heading, 'body' => $this->output));
	}

	public function list_supported_dbms()
	{
		$list = array();
		$db = array('mysql', 'mysqli', 'pgsql', 'sqlite', 'sqlite3', 'pdo_sqlite');
		$info = array(
			'mysql' => 'MySQL',
			'mysqli' => 'MySQLi',
			'pgsql' => 'PostgreSQL',
			'sqlite' => 'SQLite v2',
			'sqlite3' => 'SQLite v3',
			'pdo_sqlite' => 'SQLite via PDO',
		);
		foreach($db as $val)
		{
			if(extension_loaded($val))
			{
				$list[] = array('type' => $info[$val], 'status' => $this->green('Supported'));
			}
			else
			{
				$list[] = array('type' => $info[$val], 'status' => $this->red('Unsupported'));
			}
		}
		return $list;
	}

	public function get_supported_dbms()
	{
		$list = array();
		$db = array('mysql', 'mysqli', 'pgsql', 'sqlite', 'sqlite3', 'pdo_sqlite');
		foreach($db as $val)
		{
			if(extension_loaded($val))
			{
				$list[] = $val;
			}
		}
		return $list;
	}

	public function driver_form()
	{
		$drivers = $this->scan_drivers();

		$html = '<select name="driver" class="form">';
		foreach($drivers as $driver => $name)
		{
			$html .= '<option value="' . $driver . '">' . $name . '</option>';
		}
		$html .= '</select>';

		return $html;
	}

	public function scan_drivers()
	{
		$drivers = array();
		$iterator = new DirectoryIterator('../sources/database/drivers/');
		include '../sources/database/dbMaster' . EXT;
		foreach ($iterator as $fileinfo) {
			$ext = strtolower(strrchr($fileinfo->getFilename(), '.'));
			if (!$fileinfo->isDot() && $ext == EXT) {
				switch($iterator->getType())
				{
					case 'file':
						include $iterator->getPath() . '/' . $fileinfo->getFilename();
						$p = explode('.', $fileinfo->getFilename());
						$file = $p[0];
						$driver = 'driver' . ucfirst(strtolower($file));
						$db = new $driver;
						if($db->can_run())
						{
							$drivers[$file] = $db->driver;
						}
					break;
				}
			}
		}
		unset($db);
		return $drivers;
	}
	public function do_env_checks()
	{
		$checks = array();
		$results = array('db' => '');
		$checks['php'] = version_compare($this->base->lib->phpversion, '5.1.0', '>=');
		$checks['mbstring'] = extension_loaded('mbstring');
		$checks['reflection'] = extension_loaded('reflection');
		$checks['cache'] = (is_readable('../cache/') && is_writable('../cache/'));
		$checks['db'] = (count($this->get_supported_dbms()) == 0 ? FALSE : TRUE);
		
		if($checks['php'])
		{
			$results['php'] = $this->green('PHP ' . $this->base->lib->phpversion . ' detected');
		}
		else
		{
			$results['php'] = $this->red('PHP ' . $this->base->lib->phpversion . ' detected');
		}

		if($checks['mbstring'])
		{
			$results['mbstring'] = $this->green('Loaded');
		}
		else
		{
			$results['mbstring'] = $this->red('Unavailable');
		}

		if($checks['reflection'])
		{
			$results['reflection'] = $this->green('Loaded');
		}
		else
		{
			$results['reflection'] = $this->red('Unavailable');
		}

		if($checks['cache'])
		{
			$results['cache'] = $this->green('Writable & Readable');
		}
		else
		{
			$results['cache'] = $this->red('Failed');
		}

		if(!$checks['db'])
		{
			$results['db'] = '<p>' . $this->red('Your PHP Installation has no DB Interfaces!') . '</p>';
		}
		
		return $results;
	}
}

?>